package com.dongdong.service.impl;


import com.dongdong.api.AddressApi;
import com.dongdong.model.TbUser;
import com.dongdong.result.Result;

import com.dongdong.result.ResultEnums;
import com.dongdong.service.EmailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;




@Service
public class EmailServiceImpl implements EmailService {

    @Autowired
    private AddressApi addressApi;

    @Value("${spring.mail.username}")
    private String username;
    @Value("${spring.mail.host}")
    private String host;
    @Autowired
    private JavaMailSenderImpl javaMailSenerImpl;

    @Override
    public Result sendMail(String email) {

        TbUser user = addressApi.queryUserByEmail(email);
        //用户注册时的邮箱
        String userEmail = user.getEmail();

        //邮箱类型
        javaMailSenerImpl.setHost(host);
        //电子邮件消息的类。这个函数主要用于发送带有附件或HTML内容的复杂电子邮件
        MimeMessage message =  javaMailSenerImpl.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            //设置发件人
            helper.setFrom(username);
            //设置收件人
            helper.setTo(userEmail);
            //设置主题
            helper.setSubject("用于找回和重设密码");
            //具体内容
//            helper.setText("您好，这是一封用于找回密码的邮件，请点击下面的链接进行重置密码：<a href='http://localhost/user/resetPassword.html?'>重置密码</a>"true);
            helper.setText("您好，这是一封用于找回密码的邮件，请点击下面的链接进行重置密码：<a href='http://localhost/user/resetPassword.html?'>重置密码</a>", true);

            //发送邮件
            javaMailSenerImpl.send(message);
        } catch (MessagingException e) {
            e.printStackTrace();
            return Result.RESPONSE(ResultEnums.EMAIL_FAIL);  //发送失败
        }


        return Result.RESPONSE(ResultEnums.EMAIL_SUCCESS);//发送成功

    }
}
